package org.xhy.security.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        //设置响应字符集
        httpServletResponse.setContentType("application/json;charset=utf-8");

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("success",true);
        hashMap.put("message","登录成功");
        hashMap.put("data",authentication.getPrincipal());
        String jsonString = JSON.toJSONString(hashMap);

        httpServletResponse.getWriter().print(jsonString);
    }
}
